import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "index"
  },
  {
    /*
    * 入口
    * */
    path: "/index",
    name: "index",
    component: () => import('@/views/index/index')
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,

  // 页面滚动行为
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      if (to.path.includes('home')) return to.meta
      return savedPosition
    } else if (to.name === 'discover' || to.name === 'system' || to.name === 'mine'){
      return to.meta
    } else {
      return {
        x: 0, y: 0
      }
    }
  }
});

// 自动工程化载入 router 下面的所有路由文件
const routerList = [];
const requireContext = require.context("./", true, /\.js$/);
requireContext.keys().forEach(filename => {
  if (filename === "./index.js") return;
  routerList.push(requireContext(filename).default);
  routerList.forEach(item => {
    router.addRoutes(item.options.routes);
  });
});

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router;
